package util

import (
	"fmt"
	"time"
)

func RecoverPanic() {
	if err := recover(); err != nil {
		fmt.Printf("recover panic:%+v", err)
	}
}

type Fn func()
type Fn1[T any] func(T)
type Fn2[T1 any, T2 any] func(T1, T2)

func RunN(f Fn) {
	go func() {
		defer RecoverPanic()
		f()
	}()
}

func RunAfterN(d time.Duration, f Fn) {
	go func() {
		defer RecoverPanic()
		c := make(chan int)
		time.AfterFunc(d, func() {
			f()
			c <- 1
		})
		<-c
	}()
}

// 阻塞执行,在d的时间后放开
func RunBlockUtilN(d time.Duration, f Fn) chan int {
	c := make(chan int)
	go func() {
		defer RecoverPanic()
		time.AfterFunc(d, func() {
			c <- 1
		})
		f()
	}()
	return c
}

func RunN1[T any](f Fn1[T], p T) {
	go func(t T) {
		defer RecoverPanic()
		f(t)
	}(p)
}

func RunN2[T1 any, T2 any](f Fn2[T1, T2], p1 T1, p2 T2) {
	go func(t1 T1, t2 T2) {
		defer RecoverPanic()
		f(t1, t2)
	}(p1, p2)
}
